package main

import (
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"log"
	"net/http"
	"strings"
)

var jwtKey = []byte("secret")

const (
	authKey = "root123"
)

// Key Auth 中间件提供了一个基于密钥的验证方式。
//
// 对于有效密钥，它将调用下一个处理程序。
// 对于无效密钥，它会发送 “401 - Unauthorized” 响应。
// 对于丢失密钥，它发送 “400 - Bad Request” 响应。
func main() {

	e := echo.New()

	e.GET("/index", Index)

	////方式一：直接使用，会自动从请求头中获取authKey KeyLookup: "header:Authorization:Bearer "
	userGroup := e.Group("/default", middleware.KeyAuth(func(key string, c echo.Context) (bool, error) {
		return key == authKey, nil
	}))
	userGroup.GET("/get", GetUserInfo)

	//方式二： 自定义config,会自动从请求头中获取authKey KeyLookup： "header:Auth:RZ "
	carGroup := e.Group("/custom")
	carGroup.Use(middleware.KeyAuthWithConfig(CustomKeyAuthConfig()))
	carGroup.GET("/get", GetUserInfo)

	e.Start(":80")
}

func CustomKeyAuthConfig() middleware.KeyAuthConfig {
	c := middleware.KeyAuthConfig{
		Skipper: func(c echo.Context) bool {
			uri := c.Request().RequestURI
			if strings.Contains(uri, "/index") {
				log.Println("uri:", uri, "--->>>Skipper-true")
				return true
			}
			log.Println("uri:", uri, "--->>>Skipper-false")
			return false
		},
		Validator: func(key string, c echo.Context) (bool, error) {
			if key == authKey {
				return true, nil
			}
			return false, nil
		},
		ErrorHandler: func(err error, c echo.Context) error {
			return c.String(http.StatusUnauthorized, "AuthKey Error")
		},
		KeyLookup: "header:Auth:RZ ",
	}
	return c
}

func Index(c echo.Context) error {
	return c.String(http.StatusOK, "authKey:"+authKey)
}

func GetUserInfo(c echo.Context) error {
	user := User{
		UserId:   1,
		UserName: "admin",
		Password: "123456",
		Email:    "admin@qq.com",
	}
	return c.JSON(http.StatusOK, user)
}

type User struct {
	UserId   int    `json:"userid"`
	UserName string `json:"username"`
	Password string `json:"password"`
	Email    string `json:"email"`
}
